﻿using LJ.WebApi.Abstractions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace LJ.WebApi.Mvc.Filters;



public sealed class UnifyActionFilter : IAsyncActionFilter, IOrderedFilter
{
    /// <summary>
    /// 排序属性
    /// </summary>
    public int Order => 0;

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var webApiActionHandlers = context.HttpContext.RequestServices.GetServices<IWebApiActionHandler>();

        foreach (var webApiActionHandler in webApiActionHandlers.OrderBy(a => a.Seq))
        {
            var result =await webApiActionHandler.BeforeExecuteAsync(context.HttpContext.RequestServices, context.Controller.GetType());
            if (result != null)
            {
                context.Result = new ObjectResult(result);
                context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                return;
            }
        }

        await next();

        foreach (var webApiActionHandler in webApiActionHandlers.OrderByDescending(a => a.Seq))
        {
            var result =await webApiActionHandler.AfterExecuteAsync(context.HttpContext.RequestServices, context.Controller.GetType());
            if (result != null)
            {
                context.Result = new ObjectResult(result);
                context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                return;
            }
        }
    }
}